<template>
    <el-card v-loading="loading" shadow="never" class="smart-reply-form">
        <div class="container" @scroll="onScroll" >
            <el-form ref="formRef" :model="formData" :rules="rules" label-position="right" label-width="auto">
                <aside class="form-title">基本信息</aside>
                <el-form-item label="规则名称" prop="title">
                    <el-input v-model.trim="formData.title" maxlength="20" :show-word-limit="true" placeholder="请输入规则名称" />
                </el-form-item>
                <el-form-item label="关键词" prop="keyword" class="keywords">
                    <template #label>
                        <tootip-header label="关键词"
                            content="客户发送的内容，只要满足其中一种关键词规则，即可触发；同组内关键词为“或”的关系，多组之间关键词为“且”的关系；同一组关键词不可重复" />
                    </template>
                    <el-radio-group v-model="formData.keyword.type">
                        <el-radio :label="1">手动录入</el-radio>
                        <el-radio :label="2">批量导入</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item v-if="formData.keyword.type === 1" label=" " class="keywords-list-form">
                    <add-button :max="5" :length="formData.keyword.groups.length" @click="addKeywordGroup">
                        添加一组关键词
                    </add-button>
                    <div class="keyword-list">
                        <el-form-item
                            v-for="(item, index) in formData.keyword.groups"
                            :key="index"
                            prop="keyword.groups"
                            :rules="{
                                index: index,
                                validator: checkKeywordGroups,
                                trigger: 'blur',
                            }"
                            class="keyword-item"
                        >
                            <div class="keyword-label">
                                <div>词组{{ index + 1 }}:</div>
                                <div>
                                    <el-button v-if="formData.keyword.groups.length > 1" type="primary" link
                                        @click="removeKeyWordGroup(index)">
                                        删除
                                    </el-button>
                                </div>
                            </div>
                            <div class="keyword-group-list">
                                <div v-for="(keyItem, index) in item" class="keyword-group-item">
                                    <el-input v-model.trim="keyItem.value" maxlength="20" :show-word-limit="true"
                                        placeholder="请输入关键词">
                                        <template #prepend>
                                            <el-select v-model="keyItem.type" placeholder="请选择">
                                                <el-option label="包含" :value="1" />
                                                <el-option label="完全匹配" :value="2" />
                                            </el-select>
                                        </template>
                                    </el-input>
                                    <el-icon v-if="item.length > 1" size="16px" color="#ccc"
                                        @click="removeKeyWord(item, index)">
                                        <CircleCloseFilled />
                                    </el-icon>
                                </div>
                                <add-button :max="20" :length="item.length" @click="addKeyword(item)">
                                    添加关键词
                                </add-button>
                            </div>
                        </el-form-item>
                    </div>
                </el-form-item>
                <el-form-item v-if="formData.keyword.type === 2" label=" " class="keywords-upload-form" prop="keyword.fileCode">
                    <el-upload ref="upload" :disabled="uploadLoading" v-model:file-list="fileList" :limit="1" accept=".xlsx,.xls"
                        :on-exceed="handleExceed" :before-upload="handleBeforeUpload" :http-request="handleHttpRequest" :on-remove="handleRemove" >
                        <template #trigger>
                            <el-button type="primary" :loading="uploadLoading" >{{
                                fileList.length ? "重新上传" : "点击上传"
                            }}</el-button>
                            <el-button type="primary" link @click.stop="downLoadKeyWordTemplate">下载模板</el-button>
                        </template>
                        <template #tip>
                            <div class="el-upload__tip">
                                只能上传excel文件，且不超过2M，每个sheet页为一组关键词
                            </div>
                        </template>
                    </el-upload>
                </el-form-item>
                <el-form-item label=" ">
                    <div class="desc">
                        注：请注意若客户发送的关键词命中多条规则，则按照最新创建的规则进行回复
                    </div>
                </el-form-item>
                <el-form-item v-if="isGroupType" label="选择群聊" prop="custGroupFilter" class="cust-label-form">
                    <ZWSelectGroup v-model="formData.custGroupFilter" :option="modelOption" show-count="never" :select-disabled="selectDisabled" @submit-after="handleSubmitAfter" >
                        <template #radioOption>
                            <el-radio :label="1">
                                <span>全部外部群</span>
                                <el-tooltip content="本企业成员创建的外部群中，包含“我”的群聊。" placement="top">
                                    <el-icon class="group-tootip-icon" color="#ccc" ><QuestionFilled /></el-icon>
                                </el-tooltip>
                            </el-radio>
                            <el-radio :label="2">选择外部群</el-radio>
                        </template>
                    </ZWSelectGroup>
                    <div class="estimated-number-form" >(共选择 <span class="estimated-number">{{ estimatedNumber }}</span>个群聊)</div>
                </el-form-item>
                <el-form-item v-else label="关联客户" prop="custFilter" class="cust-label-form">
                    <template #label>
                        <tootip-header label="关联客户" content="仅适用于有企业微信好友的用户" />
                    </template>
                    <el-radio-group v-model="formData.custFilter.type">
                        <el-radio :label="1">全部客户</el-radio>
                        <el-radio :label="2">标签筛选</el-radio>
                    </el-radio-group>
                    <div v-if="formData.custFilter.type === 2" class="cust-label-filter">
                        <el-select v-model="formData.custFilter.filterType" placeholder="请选择">
                            <el-option label="包含以下任一标签" :value="1" />
                            <el-option label="包含以下所有标签" :value="2" />
                            <el-option label="不包含以下任一标签" :value="3" />
                            <el-option label="不包含以下所有标签" :value="4" />
                            <el-option label="标签为空" :value="5" />
                            <el-option label="标签不为空" :value="6" />
                        </el-select>
                        <template v-if="![5, 6].includes(formData.custFilter.filterType)">
                            <add-button :max="Infinity" @click="handleOpenSelectLabel">
                                添加标签
                            </add-button>
                            <div>
                                已选择标签 <span>{{ formData.custFilter.tags.length }}</span> 个
                            </div>
                            <render-tags v-model:tags="formData.custFilter.tags" @open-more="handleOpenSelectLabel" />
                        </template>
                    </div>
                </el-form-item>
                <el-form-item v-if="isGroupType" label="群内被@触发" prop="altEnable">
                    <el-switch v-model="formData.altEnable" :active-value="1" :inactive-value="2" />
                    <span class="switch-tip">开启此功能，当前员工在群内被用户@且用户发送的内容匹配以上设置的关键词规则（同一句话），才会被触发自动回复</span>
                </el-form-item>
                <aside class="form-title">自动回复设置</aside>
                <el-form-item label="回复内容" prop="speechCraft" class="enable-time-form">
                    <SpeechcraftListForm ref="speechcrafFormRef" v-model="formData.speechCraft" :is-group-type="isGroupType" />
                </el-form-item>
                <el-form-item label="启用时段" prop="enableTime" class="enable-time-form">
                    <el-radio-group v-model="formData.enableTime.type" @change="handleEnableTimeTypeChange" >
                        <el-radio :label="1">全部时段</el-radio>
                        <el-radio :label="2">固定时段（客户在自定义时间段内发送消息会触发）</el-radio>
                    </el-radio-group>
                    <div v-if="formData.enableTime.type === 2" class="enable-time-list">
                        <div v-for="(timeItem, index) in formData.enableTime.time" :key="index" class="enable-time-item">
                            <el-time-picker v-model="timeItem.time" is-range range-separator="至" start-placeholder="开始时间"
                                end-placeholder="结束时间" />
                            <el-icon v-if="formData.enableTime.time.length > 1" size="16px" color="#ccc"
                                @click="removeEnableTime(index)">
                                <CircleCloseFilled />
                            </el-icon>
                        </div>
                        <add-button :max="3" :length="formData.enableTime.time.length" @click="addEnableTime">
                            添加时间段
                        </add-button>
                    </div>
                </el-form-item>
                <el-form-item label="回复方式" prop="replyType">
                    <template #label>
                        <tootip-header label="回复方式" content="为防止企微风控，会在用户触发之后延迟1-60秒自动回复" />
                    </template>
                    <el-radio-group v-model="formData.replyType">
                        <el-radio :label="1">全部回复</el-radio>
                        <el-radio :label="2">随机回复一条（随机选择回复内容中的一条话术进行回复）</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item v-if="isGroupType" label="防骚扰限制" prop="replayLimit" class="replay-limit-form">
                    <el-switch v-model="formData.replayLimitSwitch" />
                    <div v-if="formData.replayLimitSwitch">
                        为防止消息骚扰，在上一次自动回复后的
                        <el-input-number
                            v-model="formData.replayLimit"
                            :min="1"
                            :max="60"
                            :precision="0"
                            placeholder="请输入"
                            controls-position="right"
                            @blur="handleBlurSetMin(1)"
                        />
                        秒内发送了多条关键词，将只回复1条，不重复回复
                    </div>
                </el-form-item>
                <el-form-item v-else label="重发限制" prop="replayLimit" class="replay-limit-form">
                    <el-switch v-model="formData.replayLimitSwitch" />
                    <div v-if="formData.replayLimitSwitch">
                        为防止消息骚扰，在本条规则的上一次自动回复后，在
                        <el-input-number
                            v-model="formData.replayLimit"
                            :min="5"
                            :max="1440"
                            :precision="0"
                            placeholder="请输入"
                            controls-position="right"
                            @blur="handleBlurSetMin(5)"
                        />
                        分钟内，不再重复触发此规则回复
                    </div>
                </el-form-item>
            </el-form>
        </div>
        <div class="operat-buttons">
            <el-button @click="onRouteBack">取消</el-button>
            <el-button type="primary" @click="submitForm(formRef, 2)">保存</el-button>
            <el-button type="primary" @click="submitForm(formRef, 1)">保存并开启</el-button>
        </div>
        <ZWSelectLabel v-model="labelVisiable" ref="zwSelectLabelRef" @submit="handleSelectLabelSubmit" />
    </el-card>
</template>

<script lang="ts" setup>
import ZWSelectGroup from "@renderer/components/win/ZWSelectGroup/ZWSelectGroup.vue";
import { ElMessage, ElMessageBox, FormInstance, FormRules, genFileId } from "element-plus";
import type { UploadInstance, UploadRawFile } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import { computed, nextTick, onBeforeMount, onMounted, reactive, ref, watchEffect } from "vue";
import dayjs from "dayjs";
import isBetween from "dayjs/plugin/isBetween";

import ZWSelectLabel from "@renderer/components/win/ZWSelectLabel/ZWSelectLabel.vue";
import {
    createSmartReplySingle,
    getSmartReplySingleDetail,
    createSmartReplyChat,
    getSmartReplyChatDetail,
    getReplyEstimatedNumber
} from '@renderer/ajax/api/smartReply'
import { uploadFile2 } from '@renderer/ajax/api/common'
import { toBuffer } from '@renderer/utils/utils'
import { GROUP_TYPE_MAP, OWNER_TYPE_MAP } from '@renderer/components/win/ZWSelectGroup/enum'

import SpeechcraftListForm from './components/control-form/speechcraft-list-form.vue'
import TootipHeader from "./components/tootip-header.vue";
import AddButton from "./components/add-button.vue";
import RenderTags from "./components/render-tags.vue";
import { getCreateParamsByFormData, handleMergeFormData } from "./paramsManager";
import axios from "axios";

const { ipcRenderer } = require("electron");
const fs = require('fs')
const path = require('path')
const { TextEncoder } = require('util');

// 校验两者之间的插件
dayjs.extend(isBetween)

const router = useRouter();
const route = useRoute();

/**
 * 页面是否是新建群聊规则
 */
 const isGroupType = computed(() => {
    return route.query.type === 'groupChat'
})

/**
 * 页面是否是编辑页面
 */
 const isEdit = computed(() => {
    return route.query.pageType === 'edit'
})

onMounted(() => {
    // 页面打开时如果是新建群聊，则默认给个10
    if (isGroupType.value) {
        formData.replayLimitSwitch = true
        formData.replayLimit = 10
    }
})

const formRef = ref<FormInstance>();
const formData = reactive({
    // 接口字段：
    id: 0, // 0 新增， 非 0 编辑
    title: "",
    //回复方式 1， 全部 2 随机
    replyType: 1,
    // 重发限制开关，前端用
    replayLimitSwitch: true,
    // 重发限制 0 无限制， (传给后端需要换算成秒数，目的是防止后续有秒的概念)
    replayLimit: 30,
    // 1 被 @ 触发， 2 关闭被@触发
    altEnable: 2,
    // 是否启用 0 不做修改， 1 启用， 2 关闭，
    status: 1,
    keyword: { // 关键词
        type: 1, // 1 手动录入， 2 文件,
        fileCode: 0, // 文件类型的关键词需要此Code
        fileInfo: { // 仅回显用
            // 文件code
            code: '',
            // 文件路径
            path: '',
            // web 请求URL
            url: '',
            // 文件名称
            name: ''
        },
        groups: [ //
            [ // 词组
                {
                    type: 1, // 1 包含， 2 完全匹配,
                    value: '',
                }
            ]
        ]
    },
    // 客户过滤
    custFilter: {
        // 1 全部客户， 2 标签筛选
        type: 1,
        // 1 包含任一、 2 包含所有 3 不包含任一 4 不包含所有 5 标签为空 6 标签不为空
        filterType: 1,
        tags: [],
    },
    // 客户群过滤
    custGroupFilter: {
        // 1 全部客户群， 2 指定客户群
        type: 1,
        // 群聊ID
        chatId: []
    },
    // 话术
    speechCraft: [
        {
            id: 0, // 话术组件ID, 为 空0时，表示新增
            text: '',
            attachments: []
        }
    ],
    // 启用时段 
    enableTime: {
        // 1 全部 2固定时段
        type: 1,
        time: [
            {
                // 前端用的开始时间
                time: [],
                // 后端开始时间
                beginTime: "",
                // 后端用的结束时间
                endTime: ""
            }
        ]
    },
});

/* ----------------------------保存和取消按钮&校验-start---------------------------- */
/**
 * 校验固定时间段
 */
const checkEnableTime = (rule: any, value: any, callback: any) => {
    // 选择全部时间段不校验
    if (formData.enableTime.type === 1) {
        return callback()
    }
    // 双循环判断时间是否重复
    for (const timeItem of formData.enableTime.time) {
        const { time } = timeItem
        const [beginTime, endTime] = time
        if (!beginTime || !endTime) {
            return callback(new Error('请选择启用时段'))
        }
        // 校验的时间
        for (const checkTimeItem of formData.enableTime.time) {
            const { time: checkTime } = checkTimeItem
            // 如果当前时间是自己，则不校验
            if (checkTime === time) {
                continue;
            }
            const [checkBeginTime, checkEndTime] = checkTime
            const beginCheckResult = dayjs(beginTime).isBetween(checkBeginTime, checkEndTime)
            const endCheckResult = dayjs(endTime).isBetween(checkBeginTime, checkEndTime)
            // 如果有任一一个是重复了，则校验失败
            if (beginCheckResult || endCheckResult) {
                return callback(new Error('时间段不能交叉'))
            }
        }
    }
    callback()
}

/**
 * 校验关联客户
 */
const checkCustFilter = (rule: any, value: any, callback: any) => {
    // 选择全部客户不校验
    if (formData.custFilter.type === 1) {
        return callback()
    }

    // 选择5 标签为空 6 标签不为空的情况下不校验
    if ([5, 6].includes(formData.custFilter.filterType)) {
        return callback()
    }

    if (!formData.custFilter.tags.length) {
        return callback(new Error('请添加标签'))
    }
    callback()
}

/**
 * 校验群聊
 */
 const checkCustGroupFilter = (rule: any, value: any, callback: any) => {
    // 选择全部客户不校验
    if (formData.custGroupFilter.type === 1) {
        return callback()
    }

    if (!formData.custGroupFilter.chatId.length) {
        return callback(new Error('请选择关联群聊'))
    }
    callback()
}


/**
 * 校验关键词
 */
const checkKeywordGroups = (rule: any, value: any, callback: any) => {
    const index = rule.index

    // 文件形式不校验
    if (formData.keyword.type !== 1) {
        return callback()
    }

    const keywordGroup = (formData.keyword.groups?.[index] || []).map(item => item.value)
    // 校验关键词组是否填写
    for (let keyIndex = 0; keyIndex < keywordGroup.length; keyIndex++) {
        const keyItem = keywordGroup[keyIndex]
        if (!keyItem) {
            return callback(new Error(`请输入【词组${index + 1}】第${keyIndex + 1}条关键词`))
        }
    }

    // 校验重复
    if (keywordGroup.length !== Array.from(new Set(keywordGroup)).length) {
        return callback(new Error(`关键词【词组${index + 1}】内容重复`))
    }
    callback()
}

/**
 * 校验关键词模版文件必填
 */
const checkKeyWordFile = (rule: any, value: any, callback: any) => {
    if (!formData.keyword.fileCode && formData.keyword.type === 2) {
        return callback(new Error('请上传关键词文件'))
    }
    callback()
}

/**
 * 校验话术
 */
const checkSpeechCraft = (rule: any, value: any, callback: any) => {
    if (!formData.speechCraft?.length) {
        return callback(new Error('请添加回复内容'))
    }

    // 校验关键词组是否填写
    for (let speechIndex = 0; speechIndex < formData.speechCraft.length; speechIndex++) {
        const speechCraftItem = formData.speechCraft[speechIndex]
        if (!speechCraftItem.text) {
            return callback(new Error(`请添加回复内容【话术${speechIndex + 1}】的话术`))
        }
    }
    return callback()
}

/**
 * 回复方式
 */
 const checkReplyType = (rule: any, value: any, callback: any) => {
    if (![1, 2].includes(formData.replyType)) {
        return callback(new Error('请选择回复方式'))
    }
    callback()
}

/**
 * 校验重发限制
 */
 const checkReplayLimit = (rule: any, value: any, callback: any) => {
    // 未开启的情况下不校验
    if (!formData.replayLimitSwitch) {
        return callback()
    }

    if (!formData.replayLimit) {
        return callback(new Error('请输入重发限制'))
    }
    // 群聊校验1～60
    // 私聊校验5～1440
    let min = isGroupType.value ? 1 : 5
    let max = isGroupType.value ? 60 : 1440


    if (formData.replayLimit < min || formData.replayLimit > max) {
        return callback(new Error(`请输入${min}~${max}之间`))
    }
    callback()
}

const rules = reactive<FormRules>({
    title: [{ required: true, message: "请输入规则名称", trigger: "blur" }],
    keyword: [{ required: true, message: "请输入任务标题", trigger: "blur" }],
    custFilter: [{ required: true, validator: checkCustFilter, trigger: "blur" }],
    custGroupFilter: [{ required: true, validator: checkCustGroupFilter, trigger: "blur" }],
    enableTime: [{ required: true, validator: checkEnableTime }],
    'keyword.fileCode': [{ validator: checkKeyWordFile }],
    speechCraft: [{ required: true, validator: checkSpeechCraft }],
    replyType: [{ required: true, validator: checkReplyType }],
    replayLimit: [{ required: true, validator: checkReplayLimit, trigger: "blur" }],
    altEnable: [{ required: true, message: "请选择群内@被触发" }]
});
const onRouteBack = () => {
    router.back();
};
const submitForm = async (formEl: FormInstance | undefined, status) => {
    if (!formEl) return;
    try {
        await formEl.validate();

        // 校验是否存在已解散的
        if (isGroupType.value) {
            await computedReplyEstimatedNumber()
            if (formData.custGroupFilter.chatId.some((item: any) => item.isDelete)) {
                await ElMessageBox.alert('系统已为您自动删除【已解散】的群聊！', '提示', {
                    confirmButtonText: '好的',
                })
            }
        }

        formData.status = status;
        const params = getCreateParamsByFormData(formData, { isEdit: isEdit.value, isGroup: isGroupType.value })
        const api = isGroupType.value ? createSmartReplyChat : createSmartReplySingle
        const res: any = await api(params)

        // 处理成功
        ElMessage.success(`${ isEdit.value ? '编辑' : '新增'}成功`)
        router.back()
        return
    } catch (err) {
        let firstError = null
        // 判断是否是错误信息。防止接口报错也会拦截的情况
        for (const errItem of Object.entries(err)) {
            firstError = firstError || errItem
            if (!Array.isArray(errItem?.[1])) {
                return
            }
        }
        
        
        // 提示第一条错误信息
        const [key, value] = firstError
        if(value?.[0]?.message) {
            ElMessage.warning(value?.[0]?.message)
        }

    }
    
};
/* ----------------------------保存和取消按钮&校验-end---------------------------- */

/* ----------------------------关键词-start---------------------------- */
/**
 * 给关键词组新增关键词
 * @param keyWordItem 当前的关键词组
 */
const addKeyword = (keyWordItem) => {
    keyWordItem.push({
        type: 1, // 1 包含， 2 完全匹配,
        value: '',
    });
};
/**
 * 删除关键词
 * @param keyWordItem 当前的关键词组
 * @param index 需要删除的序号
 */
const removeKeyWord = async (keyWordItem, index) => {
    keyWordItem.splice(index, 1);
    await nextTick()
    formRef.value.validateField(['keyword.groups'])
};

/**
 * 添加一组关键词
 */
const addKeywordGroup = () => {
    formData.keyword.groups.push([
        {
            type: 1, // 1 包含， 2 完全匹配,
            value: '',
        },
    ]);
};

/**
 * 删除一组关键词
 * @param index 需要删除的序号
 */
const removeKeyWordGroup = (index) => {
    formData.keyword.groups.splice(index, 1);
};
/* ----------------------------关键词-end---------------------------- */

/* ----------------------------关键词上传模板-start---------------------------- */

/**
 * 下载关键词模板
 */
const downLoadKeyWordTemplate = async () => {
    const res: any = await axios.get('https://bkt-scrm-test.oss-cn-shanghai.aliyuncs.com/wintools-tpl/smart-keyword-tpl.xlsx', {
        responseType: 'arraybuffer',
    })
      let params = {
        title: '请选择下载文件的目录',
        buttonLabel: '保存',
        pathName: '智能回复关键词导入模板.xlsx',
      }
      let buf = toBuffer(res.data)
      ipcRenderer.invoke("open-savebox", params).then((res) => {
        fs.writeFileSync(res.filePath, buf)
        res && ElMessage.success('导出成功')
      });
};

const upload = ref<UploadInstance>();
const fileList = ref([]);
/**
 * 上传关键词文件超出
 */
const handleExceed = (files) => {
    const file = files[0] as UploadRawFile;

    if (handleBeforeUpload(file)) {
        upload.value?.clearFiles();
        file.uid = genFileId();
        upload.value?.handleStart(file);
        upload.value?.submit();
    }
};

/**
 * @desc 上传校验;
 */
const handleBeforeUpload = (rawFile: UploadRawFile) => {
    const type = ["xlsx", "xls"];
    const filetype = rawFile.name.split(".").pop() ?? "";
    if (!type.includes(filetype)) {
        ElMessage.warning(`请上传${type.join("、")}文件!`);
        return false;
    }

    // 大于2m不允上传
    if (rawFile.size >= 1024 * 1024 * 2) {
        ElMessage.warning(`请上传2M以内的文件!`);
        return false;
    }
    return true;
};

/**
 * 自定义删除
 */
const handleRemove = () => {
    formData.keyword.fileCode = 0
}

/**
 * 是否正在上传
 */
const uploadLoading = ref(false)
/**
 * 上传
 */
const handleHttpRequest = async (rawFile) => {
    try {
        uploadLoading.value = true
        const res = await uploadFile2(rawFile.file)

        formData.keyword.fileCode = res.code
        formRef.value.validateField(['keyword.fileCode'])
        
    } catch (err) {
        upload.value?.clearFiles();
    } finally {
        uploadLoading.value = false
    }

};
/* ----------------------------关键词模板-end---------------------------- */

/* ----------------------------标签-start---------------------------- */
const labelVisiable = ref(false);
/** 选择标签弹窗示例 */
const zwSelectLabelRef = ref();
/**
 * 打开标签弹窗
 */
const handleOpenSelectLabel = () => {
    zwSelectLabelRef.value.open(formData.custFilter.tags);
};

const handleSelectLabelSubmit = (selectTags) => {
    formData.custFilter.tags = [...selectTags];
};
/* ----------------------------标签-end---------------------------- */

/* ----------------------------时间段-start---------------------------- */
const addEnableTime = () => {
    formData.enableTime.time.push({
        time: [],
        beginTime: '',
        endTime: ''
    })
}

/**
 * 移除当前索引时间段
 */
const removeEnableTime = (index) => {
    formData.enableTime.time.splice(index, 1)
    formRef.value.validateField(['enableTime'])
}

/**
 * 切换启用时段类型
 * 不校验，补充时间段
 */
const handleEnableTimeTypeChange = async () => {
    await nextTick() 
    formRef.value.clearValidate(['enableTime'])

    // 切换为全部时间段不做任何的操作
    if (formData.enableTime.type !== 2) {
        return
    }
    // 切换为固定时间段，判断是否有内容，有的话不做任何的操作
    if (formData.enableTime.time?.length) {
        return
    }
    // 否则补充一条默认选择的时间
    formData.enableTime.time= [
        {
            time: [],
            beginTime: '',
            endTime: ''
        }
    ]
}
/* ----------------------------时间段-end---------------------------- */

/* ----------------------------群聊选择-start---------------------------- */
const modelOption = reactive({
    type: 'type',
    selected: 'chatId'
})

// 禁用内部群
const selectDisabled = reactive([
{
        key: 'selectType',
        value: GROUP_TYPE_MAP['内部群'],
        defaultSelected: GROUP_TYPE_MAP['外部群']
    },
    {
        key: 'ownerType',
        value: OWNER_TYPE_MAP['非本企业成员'],
        defaultSelected: OWNER_TYPE_MAP['本企业全部成员']
    }
    
])

/**
 * 确认完之后的回调，重新校验群
 */
const handleSubmitAfter = () => {
    formRef.value.validateField(['custGroupFilter'])
}
/* ----------------------------群聊选择-end---------------------------- */

/* ----------------------------重发限制-start---------------------------- */
const handleBlurSetMin = (min) => {
    formData.replayLimit = Math.max(formData.replayLimit, min)
}
/* ----------------------------重发限制-end---------------------------- */

/* ----------------------------滚动切换欢迎语-start---------------------------- */
const speechcrafFormRef = ref()
const onScroll = (e: Event) => {
    speechcrafFormRef.value?.setScrollCurrentPhone(e.target.scrollTop)
}
/* ----------------------------滚动切换欢迎语-end---------------------------- */

/* ----------------------------预计群发客户数量-start---------------------------- */
const estimatedNumber = ref(0)
const computedReplyEstimatedNumber = async () => {
    try {
        const params = {
            ...formData.custGroupFilter,
            chatId: formData.custGroupFilter.chatId.map(item => item.id)
        }
        const res: any = await getReplyEstimatedNumber(params)
        estimatedNumber.value = res
    } catch {
        estimatedNumber.value = 0
    }
}

watchEffect(() => {
    computedReplyEstimatedNumber()
})
/* ----------------------------预计群发客户数量-end---------------------------- */

/* ----------------------------回显数据-start---------------------------- */
const loading = ref(false)
onBeforeMount(async () => {
    if (!isEdit.value) {
        return
    }

    if (!route.query?.id) {
        router.back()
        ElMessage.warning('无规则id，无法编辑')
        return
    }
    loading.value = true
    
    try {
        const detailApi = isGroupType.value ? getSmartReplyChatDetail : getSmartReplySingleDetail 
        const res = await detailApi({ id: route.query.id })
        handleMergeFormData(formData, res, { isGroup: isGroupType.value })
        formData.id = Number(route.query.id)
        fileList.value = formData.keyword.fileInfo ? [formData.keyword.fileInfo] : []
    } finally {
        loading.value = false
    }
})
/* ----------------------------回显数据-end---------------------------- */
</script>
<style lang="scss" scoped>
@import "./style/index.scss";
</style>
